<?php

namespace App\Http\Controllers\admin;

use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use Illuminate\Support\Facades\Storage;

class UploadController extends Controller
{
    public function Upload(Request $request)
    {
        if ($request->ajax() && $request->isMethod('post')) {

            $file = $request->file('file');
            // 文件是否上传成功
            if ($file->isValid()) 
            {
                // 获取文件相关信息
                $ext     = $file -> getClientOriginalExtension();               // 获取源文件扩展名
                $tmpname = $file -> getRealPath();                              // 获取文件的绝对路径
                $mimeTye = $file -> getMimeType();                              // 获取文件格式
                $delfileurl = $request->delfileurl;                             //需要删除的文件url
                if($delfileurl)
                {
                    $delstatus = Storage::disk('public')->delete($delfileurl);
                    if(!$delstatus)
                    {
                        $data = [
                            'code'=>400,
                            'msg' =>'上传错误',
                            'data' =>'', 
                        ];
                        return response()->json($data,400);
                    }
                }

    			$filename = date('YmdHis',time()) . uniqid() .'.'. $ext;
               	$status = Storage::disk('public')->put($filename, file_get_contents($tmpname));
                $filename2 = 'img/'.$filename;
                if($status)
                {
                	$data = [
                	    'code'=>200,
                	    'msg' =>'上传成功',
                	    'data' =>['src'=>$filename2,'title'=>''], 
                        'src' => $filename,
                	];
                }else{
                	$data = [
                	    'code'=>400,
                	    'msg' =>'上传失败',
                	    'data' =>'', 
                	];
                }

                return response()->json($data,$status?200:400);
            }

        }
	}

}
